package com.shjy.client.wxapi;

import android.text.TextUtils;

import java.util.Iterator;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;

public class WXPayUtil {

    private static final String TAG = "WXPayUtil";

    /**
     * 生成32位随机字符串
     * @return 随机字符串
     */
    public static String generateRandomString() {

        String source = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        Random random = new Random();
        StringBuilder builder = new StringBuilder();

        for (int i = 0; i < 32; i++) {

            int position = random.nextInt(source.length());
            builder.append(source.charAt(position));
        }

        return builder.toString();
    }

    /**
     * 生成微信支付签名
     * @param parameters
     * @return 微信支付签名
     */
    public static String generateSign(SortedMap<String, String> parameters) {

        StringBuffer stringBuffer = new StringBuffer();
        Set set = parameters.entrySet();
        Iterator<SortedMap.Entry<String, String>> iterator = set.iterator();

        while (iterator.hasNext()) {

            SortedMap.Entry<String, String> entry = iterator.next();
            String key = entry.getKey();
            String value = entry.getValue();

            if (!TextUtils.isEmpty(value)) {

                stringBuffer.append(key + "=" + value + "&");
            }
        }

        stringBuffer.append("key=" + WXConfig.SECRET_KEY);
        String sign = MD5.getMessageDigest(stringBuffer.toString().getBytes()).toUpperCase();

        return sign;
    }

}
